package com.demo.patch.controller;

import java.io.File;

import org.apache.commons.io.FileUtils;

import com.demo.patch.PatchConstants;
import com.demo.patch.interceptor.PatchInterceptor;
import com.demo.patch.model.Patch;
import com.demo.patch.validator.PatchValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;

@Before(PatchInterceptor.class)
public class PatchController extends Controller {

  public void index() {
    setAttr("patchPage", Patch.dao.paginate(getParaToInt(0, 1), 10));
    render("patch.html");
  }

  public void add() {}

  @Before(PatchValidator.class)
  public void save() {
    UploadFile file = getFile("patch.fileupload", PatchConstants.UPLOADPATH);
    String filename = file.getSaveDirectory() + File.separator + file.getFileName();
    getModel(Patch.class).save(filename);
    redirect("/patch");
  }

  public void edit() {
    setAttr("patch", Patch.dao.findById(getParaToInt()));
  }

  @Before(PatchValidator.class)
  public void update() {
    getModel(Patch.class).update();
    redirect("/patch");
  }

  public void delete() {
    // 删除对应上传补丁
    String file = Patch.dao.findById(getParaToInt(), "fileupload").getStr("fileupload");
    Patch.dao.deleteById(getParaToInt());
    FileUtils.deleteQuietly(new File(file));
    redirect("/patch");
  }

  public void search() {
    String keyword = getPara("patch.name");
    Page<Patch> result;
    if(keyword == null || keyword.length() <=0){
      result = Patch.dao.paginate(getParaToInt(0, 1), 10, "select *", "from patch");
    }else{
      result = Patch.dao.paginate(getParaToInt(0, 1), 10, "select *",  "from patch where name like '%"+ keyword + "%'");
    }
    setAttr("patchPage", result);
    render("patch.html");
  }

  public void download() {
    String filepatch = Db.queryStr("select fileupload from patch where id=?", getPara());
    renderFile(new File(filepatch));
  }
}
